﻿Imports System.Net
Imports System.Text
Imports HtmlAgilityPack
Imports System.IO

Public Class WebHelper

    Private doc As HtmlDocument
    Private node As HtmlNode

    Public Sub New()
        doc = New HtmlDocument
    End Sub

    Public ReadOnly Property HtmlDoc As HtmlDocument
        Get
            Return doc
        End Get
    End Property

    Public Sub LoadWebPage(ByVal url As String)
        Dim httpReq As System.Net.HttpWebRequest
        Dim httpResp As System.Net.HttpWebResponse
        Dim httpURL As New System.Uri(url)
        Dim readString As String = String.Empty
        Dim Enc As Encoding = Nothing
        Try
            httpReq = CType(WebRequest.Create(httpURL), HttpWebRequest)
            httpResp = CType(httpReq.GetResponse(), HttpWebResponse)

            If (String.IsNullOrEmpty(httpResp.CharacterSet)) Then
                Enc = Encoding.Default
            Else
                Enc = Encoding.GetEncoding(httpResp.CharacterSet)
            End If

            Using resStream As Stream = httpResp.GetResponseStream()
                Dim reader As New StreamReader(resStream, Enc)
                readString = reader.ReadToEnd()
            End Using
            doc.LoadHtml(readString)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "LoadWepPage")
        End Try
    End Sub

    Public Function DownloadImage(ByVal url As String) As Image
        Dim res As Image = Nothing
        Try
            Dim fileReader As New WebClient()
            Dim objImage As MemoryStream
            objImage = New MemoryStream(fileReader.DownloadData(url))
            res = Image.FromStream(objImage)
        Catch ex As HttpListenerException
            MsgBox("Error accessing " + url + " - " + ex.Message)
            res = Nothing
        Catch ex As Exception
            MsgBox("Error accessing " + url + " - " + ex.Message)
            res = Nothing
        End Try
        Return res
    End Function

End Class
